<template>
  <view class="container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <text class="title">{{ id ? '编辑分类' : '新增分类' }}</text>
    </view>

    <!-- 分类表单 -->
    <uni-forms ref="form" :model="formData" :rules="rules">
      <!-- 分类名称 -->
      <uni-forms-item label="分类名称" name="name">
        <uni-easyinput v-model="formData.name" placeholder="请输入分类名称" />
      </uni-forms-item>

      <!-- 排序权重 -->
      <uni-forms-item label="排序权重" name="sort">
        <uni-easyinput type="number" v-model="formData.sort" placeholder="请输入排序权重" />
      </uni-forms-item>
    </uni-forms>

    <!-- 底部操作按钮 -->
    <view class="footer">
      <button class="cancel-btn" @click="handleCancel">取消</button>
      <button class="submit-btn" @click="handleSubmit">保存</button>
    </view>
  </view>
</template>

<script setup>
import {ref} from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getCategoryDetail, saveCategory, updateCategory } from '@/api/goodsCategory';

const form = ref(null);
const id = ref('');
const type = ref('');
const formData = ref({
  name: '',
  sort: 0,
  merchantId: ''
});

const rules = {
  name: {
    rules: [{ required: true, errorMessage: '请输入分类名称' }]
  },
  sort: {
    rules: [
      { required: true, errorMessage: '请输入排序权重' },
      { format: 'number', errorMessage: '排序权重必须为数字' }
    ]
  }
};

const handleCancel = () => {
  uni.navigateBack();
};

const handleSubmit = async () => {
  try {
    await form.value.validate();
    if (id.value) {
      await updateCategory(formData.value);
      uni.showToast({ title: '更新成功', icon: 'success' });
    } else {
      const res = await saveCategory(formData.value);
      uni.showToast({ title: '新增成功', icon: 'success' });
    }
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (e) {
    console.error('保存失败:', e);
  }
};

onLoad((options) => {
  type.value = options.type;
  if (options.id) {
    id.value = options.id;
    getCategoryDetail(options.id).then(res => {
      formData.value = { ...res.data };
    });
  }
  if (options.merchantId) {
    formData.value.merchantId = options.merchantId;
  }
});

</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
}

.header {
  margin-bottom: 40rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: $uni-text-color;
}

.footer {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  display: flex;
  padding: 20rpx 30rpx;
  background: $uni-bg-color;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.08);
}

.cancel-btn {
  flex: 1;
  margin-right: 20rpx;
  background: $uni-bg-color-grey;
  color: $text-medium;
}

.submit-btn {
  flex: 1;
  background: $primary-color;
  color: $uni-text-color-inverse;
}
</style>